package com.bigfreakindeals.DAO;

import java.util.concurrent.ConcurrentHashMap;
import android.content.Context;

public class DAOFactory {
	protected static DAOFactory _instance = null;
	protected DatabaseHelper dbHelper = null;

	public enum DAOType {
		PROFILE(1);
		
		private int value;
		DAOType(int value) { this.value = value; }
		public int value() { return value; }
		public static DAOType fromValue(int value) {
			for (DAOType e : DAOType.values()) {
				if (e.value() == value) {
					return e;
				}
			}
			return null;
		}
	}
	
	protected ConcurrentHashMap<DAOType, DAO> daoMaps = null;

	
	protected DAOFactory() {
		daoMaps = new ConcurrentHashMap<DAOType, DAO>();
	}

	protected void finalize() {
		try {
			super.finalize();
			if( dbHelper != null )
				dbHelper.close();
		} catch (Throwable e) {
			
		}
		
	}
	public void close(){
		try {
			if( dbHelper != null )
				dbHelper.close();
		} catch (Throwable e) {
			
		}
	}

	/**
	 * Get the singleton instance
	 * @return
	 */
	public synchronized static DAOFactory getInstance() {
		if( _instance == null ) {
			_instance = new DAOFactory();
		}
		return _instance;
	}
	/**
	 * Get the DAO
	 * @param <T>
	 * @param type
	 * @return
	 */
	public DAO getDAO(DAOType type, Context ctx) {
		synchronized( this.daoMaps ) {
			if ( dbHelper==null )
				dbHelper = new DatabaseHelper(ctx);
			
			if( this.daoMaps.containsKey(type) )
			{
				return this.daoMaps.get(type);
			}
			
			DAO dao = null;
			dao = new PROFILEDAO(ctx, dbHelper);
		
			
			if( dao != null )
				this.daoMaps.put(type, dao);
			return dao;
		}
	}
}
